/*
 * Copyright Owen Watson 2009
 * 
 * This file is part of ArtNotes.
 *
 * ArtNotes is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.

 * ArtNotes is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with ArtNotes.  If not, see <http://www.gnu.org/licenses/>.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.Drawing;
using MonoTouch.CoreGraphics;

namespace ArtNotes
{
	/// <summary>
	/// The Notebooks Tab Controller provides
	/// a Tabular view of all the current notebooks.
	/// The Notebooks are dynamically generated based
	/// on the tags used to categorise the stored
	/// images.
	/// </summary>
	[MonoTouch.Foundation.Register("ANNotebooksTabController")]
	public class ANNotebooksTabController : UITableViewController
	{
		public ANNotebooksTabController (IntPtr p) : base(p)
		{
		}
		
		public ANNotebooksTabController()
		{
		}

		class DataSource : UITableViewDataSource {
			
			ANNotebooksTabController nvc;
			const int kViewTag = 1;
			
			private Dictionary<int, anTableViewCell> controllers = null;
				
			public DataSource (ANNotebooksTabController  nvc)
			{
				this.nvc = nvc;
				controllers = new Dictionary<int, anTableViewCell>();
			}

			public override int RowsInSection (UITableView tableView, int section)
			{
				Console.WriteLine ("Number of items is : " + nvc.notebooks.Length.ToString ());
				return nvc.notebooks.Length;
			}
			


			
			public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
			{
				anTableViewCell cellController = null;
				
				UITableViewCell cell = tableView.DequeueReusableCell ("anCell");
				
				if (cell == null)
          		{
					cellController = new anTableViewCell ();

					NSBundle.MainBundle.LoadNib ("anTableViewCell", cellController, null);
					cell = cellController.Cell;
					
					cell.Tag = Environment.TickCount;
					controllers.Add (cell.Tag, cellController);
				}
				else
				{
					cellController = controllers[cell.Tag];
				}
				

				cellController.anCustomImageView.AutosizesSubviews = true;
				
				//Random random = new Random ();
				//float rotation = (float)(Math.PI * random.Next (-5, 5) / 180.0) ;
				
				// -----
				// HACK: needs fixing
				//ANImageUtils imageUtils = new ANImageUtils();
				//UIImage frame = UIImage.FromFile("Images/polaroid.png");
				//UIImage tmp = imageUtils.overlayImage(
				//	nvc.notebooks[indexPath.Row].Image,
				//	frame,
				//	new RectangleF (0, 0, 15, 15),
				//	new RectangleF (0, 0, 15, 15),
				//	new SizeF (15, 15)
				//	);
				// -----
				
				cellController.anCustomImageView.Image = UIImage.FromFile("Images/portfolio.png"); //tmp;
				
				//cellController.anCustomImageView.Image = imageUtils.scaleImage(UIImage.FromFile("Images/portfolio.png"),new SizeF(32,32));
				
				//cellController.anCustomImageView.Transform = CGAffineTransform.MakeRotation (rotation);
				
				String num = nvc.anDB.ListImagesForTag(new Tag(){TagName = nvc.notebooks[indexPath.Row].Title}).Count().ToString();
				cellController.anCustomTitle = nvc.notebooks[indexPath.Row].Title;// + " (" + num + ")";
				cellController.anCustomDescription = nvc.notebooks[indexPath.Row].Description;
				cellController.anImageCountImageView.Image = UIImage.FromFile("Images/red_dot_overlay.png");
				cellController.anImageCountLabel = num;
				
				UIImage exportImage = UIImage.FromFile("Images/export_mode.png");
				
				if(nvc.exportMode)
					cellController.anExportImageView.Image = exportImage;
				else
					cellController.anExportImageView.Image = UIImage.FromFile("Images/blank.png");
				
				return cell;
			}
		}
	
		class TableDelegate : UITableViewDelegate {
			
			ANNotebooksTabController nvc;
		
			public TableDelegate (ANNotebooksTabController  nvc)
			{
				this.nvc = nvc;
			}
			
			public override float GetHeightForRow (UITableView tableView, NSIndexPath indexPath)
			{
				return 95f;
			}
		
			private Image[] notebookImages;
			public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
			{
				Console.WriteLine ("Row selected {0}", indexPath.Row);
		
				// constructor should take image id from value of row
				//ANImageInfoController imageInfoController = new ANImageInfoController ();
				if(nvc.exportMode)
				{
					notebookImages = nvc.anDB.ListImagesForTag(new Tag(){TagName = nvc.notebooks[indexPath.Row].TagName}).ToArray();
					confirmExport = createConfirmExport(indexPath.Row);
					confirmExport.Show();
					Console.WriteLine("Exporting...");
					nvc.exportMode = false;
					nvc.TableView.ReloadData();
				}
				else
				{
					ANNotebookController notebookController = new ANNotebookController (nvc.notebooks[indexPath.Row].TagName);
					tableView.DeselectRow(indexPath, true);
					nvc.NavigationController.PushViewController (notebookController, true);
				}
			}
			private UIAlertView confirmExport;
			private UIAlertView createConfirmExport(int tag)
			{
				UIAlertView uia = new UIAlertView();
				uia.Tag = tag;
				uia.Title = "Export Notebook";
				uia.Message = "Are you sure you want to continue?";
				uia.AddButton("Yes");
				uia.AddButton("No");
				uia.Clicked += delegate(object sender, UIButtonEventArgs e) {
					if(e.ButtonIndex.Equals(0))
					{
						Console.WriteLine("Pressed!");
						
						for(int i =0; i< notebookImages.Length;i++)
						{
							Console.WriteLine(notebookImages[i].Title);
							UIImage tmp = UIImage.FromFileUncached(AN_APP_OPTIONS.DOC_DIR + notebookImages[i].FileName);
							tmp.SaveToPhotosAlbum(delegate{Console.WriteLine("Saved Image!");});
						}
						
						UIAlertView doneMsg = new UIAlertView();
						doneMsg.Title = "ArtNotes";
						doneMsg.Message = "Finished Exporting!";
						doneMsg.AddButton("OK");
						doneMsg.Show();
					}
				};
				return uia;
			}
			
			//public override void AccessoryButtonTapped (UITableView tableView, NSIndexPath indexPath)
			//{
				//base.AccessoryButtonTapped (tableView, indexPath);
				//ANNotebookController notebookController = new ANNotebookController (nvc.notebooks[indexPath.Row].TagName);
				
				//nvc.NavigationController.PushViewController (notebookController, true);
			//}

		}
		
		struct Notebook
		{
			public string Title, Description, TagName;
			public UIImage Image;

			public Notebook (string title, string description, UIImage image, string tagName)
			{
				Title = title;
				Description = description;
				Image = image;
				TagName = tagName;
			}
		}

		Notebook[] notebooks;
		ANDatabase anDB;
		
		public UIImage LoadImage (string filename)
		{
			UIImage img = UIImage.FromFileUncached (filename);
			return img;
		}
		
		private bool exportMode = false;
		
		public override void ViewDidLoad ()
		{
			Console.WriteLine ("ANNotebooksTabController: ViewDidLoad()");
			base.ViewDidLoad ();
			
			this.TableView.DataSource = new DataSource (this);
			this.TableView.Delegate = new TableDelegate (this);
			
			this.TableView.BackgroundColor = UIColor.Clear;
			this.TableView.SeparatorColor = UIColor.Clear;
			this.ParentViewController.View.BackgroundColor = UIColor.FromPatternImage(UIImage.FromFile("Images/notepaper.png"));
			
			NavigationItem.BackBarButtonItem = new UIBarButtonItem () { Title = "Back" };
			
			UIBarButtonItem btnExport = new UIBarButtonItem();
			btnExport.Title = "Export";
			btnExport.Clicked += delegate {
				if(exportMode)
					exportMode = false;
				else
					exportMode = true;
				
				this.TableView.ReloadData();
			};
			
			//NavigationItem.RightBarButtonItem = new UIBarButtonItem () {Title = "Export" };
			NavigationItem.RightBarButtonItem = btnExport;
			//
			anDB = AN_APP_OPTIONS.AN_DATABASE;//new ANDatabase(AN_APP_OPTIONS.DB_PATH);
		}

		public override void ViewWillAppear (bool animated)
		{
			//UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.BlackOpaque;
			//Console.WriteLine ("About Tab Visible");
			
			Tag[] tags = anDB.ListAllTags ().ToArray ();
			
			Console.WriteLine ("Total Tags: " + tags.Length.ToString ());
			notebooks = new Notebook[tags.Length];
			
			for (int i = 0; i < notebooks.Length; i++)
			{
				Console.WriteLine ("Tag " + i.ToString () + " is " + tags[i].TagName);
				notebooks[i] = new Notebook (
					tags[i].TagName,
					"",
					UIImage.FromFile ("Images/icon.png"),
					tags[i].TagName
				);
			}
			
			this.TabBarItem.BadgeValue = notebooks.Length.ToString ();
			this.TableView.ReloadData();
		}

	}
}
